<?php

namespace api\system\controller;


class AdminAssetController extends \Aaa\system\controller\AdminAssetController {

    protected function init() {
        $types = config('asset');
        $typeOptions = [];
        foreach ($types as $k => $v) {
            $typeOptions[] = ['name' => $v, 'value' => $k];
        }

        $this->baseField = [
            [
                'field' => 'id',
                'name' => 'ID',
            ],
            [
                'field' => 'user_id',
                'name' => '用户',
            ],
            [
                'field' => 'type',
                'name' => '类型',
                'type' => 'select',
                'options' => $typeOptions,
            ],
            [
                'field' => 'filename',
                'name' => '文件名',
            ],
            [
                'field' => 'file_size',
                'name' => '文件大小',
            ],
            [
                'field' => 'image',
                'name' => '图像',
                'type' => 'image',
            ],
            [
                'field' => 'file_path',
                'name' => '文件路径',
            ],
            [
                'field' => 'create_time',
                'name' => '上传时间',
                'type' => 'time',
            ],
        ];
    }

    protected function beforeIndex() {
        $this->actionField = ['id', 'user_id', 'type', 'filename', 'file_size', 'image', 'file_path', 'create_time'];
        $this->searchField = [
            'common' => [
                'id' => 'accurate',
                'user_id' => 'accurate',
                'type' => 'accurate',
                'filename' => 'fuzzy',
                'file_path' => 'fuzzy',
            ],
            'time' => ['create_time'],
            'amount' => ['file_size']
        ];
    }

    // 利用后置方法判断文件是否丢失和更改文件大小为KB
    protected function afterIndex($data) {
        foreach ($data['listData']['data'] as &$v) {
            if (file_exists('upload/' . $v['file_path'])) {
                $v['image'] = $v['file_path'];
            } else {
                $v['filename'] .= '（文件丢失）';
            }
            $v['file_size'] = round($v['file_size'] / 1024) . 'KB';
        }
        return $data;
    }

    // 利用后置方法判断文件是否丢失和更改文件大小为KB
    protected function afterView($data) {
        if (file_exists('upload/' . $data['postData']['file_path'])) {
            $data['postData']['image']=  $data['postData']['file_path'];
        } else {
            $data['postData']['filename'] .= '（文件丢失）';
        }
        return $data;
    }

}
